﻿using DevExpress.XtraEditors;
using DevTeam;
using eFatura.Utility;
using Extensions;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.ServiceModel;
using System.Windows.Forms;

namespace eFatura
{
    public static class Temel
    {
        public static string GetParabirimi(string val)
        {
            switch (val.ToUpper())
            {
                case "TRL":
                    return "TRY";
                case "TRY":
                    return "TRY";
                case "USD":
                    return "USD";
                case "EUR":
                    return "EUR";
                case "GBP":
                    return "GBP";
                case "CHF":
                    return "CHF";
            }
            return val;
        }

        public static string GetBirim(string val)
        {
            switch (val.Trim())
            {
                case "AD":
                    return "NIU";
                case "MT":
                    return "MTR";
                case "KG":
                    return "KGM";
            }
            return val;
        }

        public static string ConvertToBirim(string val)
        {
            switch (val.Trim())
            {
                case "NIU":
                    return "Adet";
                case "MTR":
                    return "Metre";
                case "KGM":
                    return "Kilogram";
            }
            return val;
        }

        public enum Senaryo
        {
            Temel = 1,
            Ticari = 2
        }

        public enum FaturaTipi
        {
            Satis = 1,
            Iade = 2,
            Tevkifat = 3,
            Istisna = 4

        }

        public class SatirBirimi
        {
            public const string Adet = "NIU";
            public const string Metre = "MTR";
            public const string Kilo = "KGM";
        }
    }

    public class Satir
    {
        public string Birim { get; set; }
        public decimal Miktar { get; set; }
        public decimal Matrah { get; set; }
        public decimal VergiTutari { get; set; }
        public string Urun { get; set; }
        public string UrunDetay { get; set; }
        public decimal BirimFiyat { get; set; }
        public decimal VergiOraniYuzde { get; set; }
    }

    public class Vergi
    {
        public string Tanim { get; set; }
        public string Parabirimi { get; set; }
        public decimal Matrah { get; set; }
        public decimal VergiOraniYuzde { get; set; }
        public decimal VergiTutari { get; set; }
        public string VergiTuru { get; set; }
        public string VergiKodu { get; set; }
    }

    public class Cari
    {
        public string Ulke { get; set; }
        public string Sehir { get; set; }
        public string Ilce { get; set; }
        public string Adres { get; set; }
        public string Unvan { get; set; }
        public string VKN { get; set; }
        public string VergiDairesi { get; set; }

        public string PostaKutusu { get; set; }
    }

    public class Doviz
    {
        public string KaynakParaBirimi { get; set; }
        public string HedefParaBirimi { get; set; }
        public decimal Kur { get; set; }
    }

    public class Fatura
    {
        public static string KullaniciAdi;
        public static string Parola;
        public static long FirmaKodu;

        public static void Init(string KullaniciAdi, string Parola, long FirmaKodu)
        {
            Fatura.KullaniciAdi = KullaniciAdi;
            Fatura.Parola = Parola;
            Fatura.FirmaKodu = FirmaKodu;
        }

        public Fatura()
        {

            BasicHttpBinding binding = new BasicHttpBinding();

            binding.Security.Mode = BasicHttpSecurityMode.Transport;
            binding.MaxReceivedMessageSize = 65536000;
            binding.ReaderQuotas.MaxStringContentLength = 5242880;

            reportService = new payReport.ReportServiceClient();
            payer = new payFlex.ClientInterfaceServiceClient();

            reportService = new payReport.ReportServiceClient(binding, reportService.Endpoint.Address);
            payer = new payFlex.ClientInterfaceServiceClient(binding, payer.Endpoint.Address);

            Anahtar.Username = KullaniciAdi;
            Anahtar.Password = Parola;
            Anahtar.InstitutionId = FirmaKodu;

            RaporAnahtar.Username = KullaniciAdi;
            RaporAnahtar.Password = Parola;
            RaporAnahtar.InstitutionId = FirmaKodu;
        }

        private payFlex.ClientInterfaceServiceClient payer;
        private payFlex.RequestHeader Anahtar = new payFlex.RequestHeader();
        private payReport.RequestHeader RaporAnahtar = new payReport.RequestHeader();
        private payReport.ReportServiceClient reportService;

        public int TakipNo { get; set; }

        public long PayFlexId { get; set; }

        public string PayFlexDurum { get; set; }

        public string eFaturaNo { get; set; }

        public string URL { get; set; }

        public string GrupOnEk { get; set; }

        public bool AsilMi { get; set; }

        public DateTime Tarih { get; set; }

        public Doviz DovizBilgileri { get; set; }

        public string Parabirimi { get; set; }

        public string Notlar { get; set; }

        public string ZarfDurum { get; set; }

        public string FaturaDurum { get; set; }

        public bool Tamamlandi { get; set; }

        public Cari Alici { get; set; }

        public Cari Gonderici { get; set; }

        public decimal VergiToplami { get; set; }

        public decimal Matrah { get; set; }

        public decimal VergiDahilTutar { get; set; }
        public decimal OdenecekTutar { get; set; }

        public Temel.Senaryo Senaryo { get; set; }

        public Temel.FaturaTipi Tip { get; set; }

        public List<Vergi> Vergiler { get; set; }

        public List<Satir> Satirlar { get; set; }

        public string Schema
        {
            get
            {
                return AppSession.Schema;
            }
        }
        public int SirketId
        {
            get
            {
                return AppSession.SirketId;
            }
        }

        private void InitFromDS()
        {
            DataSet ds = AppSession.DataManager.ExecuteDataSet(Schema + "GetGidenEFatura", TakipNo, SirketId);
            DataRow drBaslik = ds.Tables[0].Rows[0];
            DataTable dtVergiler = ds.Tables[1];
            DataTable dtSatirlar = ds.Tables[2];

            AsilMi = (bool)drBaslik["AsilMi"];

            GrupOnEk = drBaslik["GrupOnEk"].ToString();
            Senaryo = (Temel.Senaryo)drBaslik["Senaryo"];

            //Tip = (Temel.FaturaTipi)drBaslik["Tip"];
            Tarih = (DateTime)drBaslik["Tarih"];
            Parabirimi = Temel.GetParabirimi(drBaslik["Parabirimi"].ToStringNN());
            Notlar = drBaslik["Notlar"].ToStringNN();

            Alici = new Cari();
            Alici.Unvan = drBaslik["AliciUnvan"].ToStringNN();
            Alici.VKN = drBaslik["AliciVKN"].ToStringNN();
            Alici.PostaKutusu = drBaslik["AliciPostaKutusu"].ToStringNN();
            Alici.Ulke = drBaslik["AliciUlke"].ToStringNN();
            Alici.Sehir = drBaslik["AliciSehir"].ToStringNN();
            Alici.Ilce = drBaslik["AliciIlce"].ToStringNN();
            Alici.Adres = drBaslik["AliciAdres"].ToStringNN();
            Alici.VergiDairesi = drBaslik["AliciVergiDairesi"].ToStringNN();


            Gonderici = new Cari();
            Gonderici.Unvan = drBaslik["GondericiUnvan"].ToStringNN();
            Gonderici.VKN = drBaslik["GondericiVKN"].ToStringNN();
            Gonderici.PostaKutusu = drBaslik["GondericiPostaKutusu"].ToStringNN();
            Gonderici.Ulke = drBaslik["GondericiUlke"].ToStringNN();
            Gonderici.Sehir = drBaslik["GondericiSehir"].ToStringNN();
            Gonderici.Ilce = drBaslik["GondericiIlce"].ToStringNN();

            DovizBilgileri = new Doviz();
            DovizBilgileri.KaynakParaBirimi = drBaslik["KaynakParaBirimi"].ToString();
            DovizBilgileri.HedefParaBirimi = drBaslik["HedefParaBirimi"].ToString();
            DovizBilgileri.Kur = drBaslik["DovizKuru"].ToDecimalNN();

            Matrah = drBaslik["Matrah"].ToDecimalNN();
            VergiToplami = drBaslik["VergiToplami"].ToDecimalNN();
            VergiDahilTutar = drBaslik["VergiDahilTutar"].ToDecimalNN();
            OdenecekTutar = drBaslik["Odenecek"].ToDecimalNN();

            bool tevkifatMi = false;

            Vergiler = new List<Vergi>();
            foreach (DataRow drVergi in dtVergiler.Rows)
            {
                Vergi vergi = new Vergi();
                vergi.Tanim = drVergi["Tanim"].ToStringNN();
                vergi.Matrah = drVergi["Matrah"].ToDecimalNN();
                vergi.VergiOraniYuzde = drVergi["VergiOraniYuzde"].ToDecimalNN();
                vergi.VergiTutari = drVergi["VergiTutari"].ToDecimalNN();
                vergi.VergiTuru = drVergi["VergiTuru"].ToStringNN();
                vergi.VergiKodu = drVergi["VergiKodu"].ToStringNN();

                if (vergi.VergiKodu == "9015")
                    tevkifatMi = true;

                Vergiler.Add(vergi);
            }

            if (tevkifatMi)
                Tip = Temel.FaturaTipi.Tevkifat;

            Satirlar = new List<Satir>();
            foreach (DataRow drSatir in dtSatirlar.Rows)
            {
                Satir satir = new Satir();
                satir.Urun = drSatir["Urun"].ToStringNN();
                satir.UrunDetay = drSatir["UrunDetay"].ToStringNN();
                satir.Birim = Temel.GetBirim(drSatir["Birim"].ToStringNN());
                satir.BirimFiyat = drSatir["BirimFiyat"].ToDecimalNN();
                satir.Miktar = drSatir["Miktar"].ToDecimalNN();
                satir.Matrah = drSatir["Matrah"].ToDecimalNN();
                satir.VergiTutari = drSatir["VergiTutari"].ToDecimalNN();
                satir.VergiOraniYuzde = drSatir["VergiOraniYuzde"].ToDecimalNN();

                Satirlar.Add(satir);
            }
        }

        public void Gonder(int takipNo, int iade)
        {
            TakipNo = takipNo;
            if (iade == 0)
                Tip = Temel.FaturaTipi.Satis;
            else
                Tip = Temel.FaturaTipi.Iade;
            InitFromDS();
            Gonder();
        }

        private void Gonder()
        {
            #region Header
            payFlex.SendInvoicesRequest sendReq = new payFlex.SendInvoicesRequest();
            sendReq.AcceptanceDateTime = DateTime.Now; //ERP'nin gönderim tarihi
            sendReq.Header = Anahtar;


            payFlex.OutgoingInvoice gidenFatura = new payFlex.OutgoingInvoice();
            payFlex.OutgoingInvoiceHeader header = new payFlex.OutgoingInvoiceHeader();
            header.IsDraft = false;
            header.TrackNumber = TakipNo.ToStringNN();
            header.ReceiverIdentityNumber = Alici.VKN;
            header.ReceiverAlias = Alici.PostaKutusu;
            header.SenderAlias = Gonderici.PostaKutusu;
            header.InvoiceNumberPrefix = GrupOnEk;




            header.OperationSourceCode = TakipNo;

            //if (Environment.MachineName == "KGULCAN")
            //    header.IsOverrideWithRetry = true;

            gidenFatura.Header = header;

            payFlex.InvoiceBody body = new payFlex.InvoiceBody();
            body.ProfileID = (int)Senaryo;
            body.CopyIndicator = !AsilMi;
            body.IssueDateTime = Tarih;
            body.InvoiceTypeCode = (int)Tip;
            body.DocumentCurrencyCode = Parabirimi;
            body.Notes = new string[] { Notlar };

            payFlex.CustomerParty receiver = new payFlex.CustomerParty();
            receiver.Party = new payFlex.Party();
            receiver.Party.PartyName = Alici.Unvan;


            payFlex.Address receiverAddress = new payFlex.Address();
            receiverAddress.Country = new payFlex.Country();
            receiverAddress.Country.Name = Alici.Ulke;
            receiverAddress.CityName = Alici.Sehir;
            receiverAddress.CitySubdivisionName = Alici.Ilce;
            receiverAddress.StreetName = Alici.Adres;
            receiver.Party.PostalAddress = receiverAddress;

            payFlex.PartyIdentification idReceiver = new payFlex.PartyIdentification();
            idReceiver.SchemeID = "VKN";
            idReceiver.Value = Alici.VKN;

            receiver.Party.PartyTax = Alici.VergiDairesi;

            //TODO K.A : Şahıs firmalarında aşağıdaki nesne de gönderilmeli. Şahıs firmalarına yönelik bir çalışma yapılmalı. Nebimde şahıs firmalarını nasıl ayırt edeceğiz? TCno 11 karkater,VKN 10 karakter ??
            //Şahıs firması ise isim ve soyismi nasıl / nerden alacağız ? Şu an tbFirma tablosunda sAciklama alanına şirket isminden sonra - konularak şahıs ismi yazılıyor.

            //receiver.Party.Person = new payFlex.Person();
            //receiver.Party.Person.FirstName = "ÇETİN";
            //receiver.Party.Person.FamilyName = "ŞENAY";


            receiver.Party.PartyIdentifications = new payFlex.PartyIdentification[] { idReceiver };

            body.AccountingCustomerParty = receiver;

            payFlex.SupplierParty sender = new payFlex.SupplierParty();
            sender.Party = new payFlex.Party();
            sender.Party.PartyName = Gonderici.Unvan;

            payFlex.Address senderAddress = new payFlex.Address();
            senderAddress.Country = new payFlex.Country();
            senderAddress.Country.Name = Gonderici.Ulke;
            senderAddress.CityName = Gonderici.Sehir;
            senderAddress.CitySubdivisionName = Gonderici.Ilce;
            sender.Party.PostalAddress = senderAddress;

            payFlex.PartyIdentification idSender = new payFlex.PartyIdentification();
            idSender.SchemeID = "VKN";
            idSender.Value = Gonderici.VKN;
            sender.Party.PartyIdentifications = new payFlex.PartyIdentification[] { idSender };

            body.AccountingSupplierParty = sender;

            if (SirketId == 4)
            {
                sender.Party.WebsiteURI = "http://akertekstil.com/";
                //payFlex.PartyIdentification partyId = new payFlex.PartyIdentification();
                //partyId.SchemeID = "0230018278";
                //sender.Party.PartyIdentifications = new payFlex.PartyIdentification[] {partyId};
                sender.Party.PartyName = "AKER TEKSTİL KUMAŞÇILIK SAN.VE TİC.AŞ.";

                sender.Party.PostalAddress = new payFlex.Address();
                sender.Party.PostalAddress.Room = "5";
                sender.Party.PostalAddress.StreetName = "YILANLI AYAZMA YOLU MEVLEVİHANE CAD.NO.5";
                sender.Party.PostalAddress.BuildingNumber = "1";
                sender.Party.PostalAddress.CitySubdivisionName = "MALTEPE MAH.ZEYTİNBURNU";
                sender.Party.PostalAddress.CityName = "İSTANBUL";
                sender.Party.PostalAddress.Country = new payFlex.Country();
                sender.Party.PostalAddress.Country.Name = "TÜRKİYE";

                sender.Party.PartyTax = "HALİÇ KURUMLAR";

                sender.Party.Contact = new payFlex.Contact();
                sender.Party.Contact.Telephone = "(212) 482-1160";
                sender.Party.Contact.Telefax = "(212) 482-1165";
                sender.Party.Contact.ElectronicMail = "efatura@akertekstil.com";
            }


            payFlex.ExchangeRate pricingExchangeRate = new payFlex.ExchangeRate();
            pricingExchangeRate.SourceCurrencyCode = DovizBilgileri.KaynakParaBirimi;
            pricingExchangeRate.TargetCurrencyCode = DovizBilgileri.HedefParaBirimi;
            pricingExchangeRate.CalculationRate = DovizBilgileri.Kur;

            body.PricingExchangeRate = pricingExchangeRate;
            #endregion

            payFlex.TaxTotal tax = new payFlex.TaxTotal();
            tax.TaxAmount = new payFlex.Amount();
            tax.TaxAmount.CurrencyCode = Parabirimi;
            tax.TaxAmount.Value = VergiToplami;


            payFlex.TaxTotal taxTev = new payFlex.TaxTotal();
            taxTev.TaxAmount = new payFlex.Amount();
            taxTev.TaxAmount.CurrencyCode = Parabirimi;
            taxTev.TaxAmount.Value = 0;

            payFlex.TaxTotal tax0 = new payFlex.TaxTotal();
            tax0.TaxAmount = new payFlex.Amount();
            tax0.TaxAmount.CurrencyCode = Parabirimi;
            tax0.TaxAmount.Value = 0;


            List<payFlex.TaxSubtotal> AllSubTax = new List<payFlex.TaxSubtotal>();
            List<payFlex.TaxSubtotal> AllSubTevTax = new List<payFlex.TaxSubtotal>();

            #region Vergiler
            if (Vergiler.Count == 0)
            {
                payFlex.TaxSubtotal subTax = new payFlex.TaxSubtotal();

                subTax.TaxAmount = new payFlex.Amount();
                subTax.TaxAmount.CurrencyCode = Parabirimi;
                subTax.TaxAmount.Value = 0;
                subTax.TaxCategorySchemeName = "KDV";
                subTax.TaxCategorySchemeCode = "0015";
                subTax.TaxableAmount = new payFlex.Amount();
                subTax.TaxableAmount.CurrencyCode = Parabirimi;
                subTax.TaxableAmount.Value = 0;
                subTax.Percent = 0;

                subTax.TaxCategoryExemptionReason = "KDV siz";
                subTax.TaxCategoryExemptionReasonCode = "350";

                body.InvoiceTypeCode = (int)Temel.FaturaTipi.Istisna;

                AllSubTax.Add(subTax);
            }
            else
                foreach (Vergi vergi in Vergiler)
                {
                    if (vergi.VergiKodu == "9015")
                    {
                        payFlex.TaxSubtotal subTevTax = new payFlex.TaxSubtotal();
                        subTevTax.TaxAmount = new payFlex.Amount();
                        subTevTax.TaxAmount.CurrencyCode = Parabirimi;
                        subTevTax.TaxAmount.Value = vergi.VergiTutari;
                        subTevTax.TaxCategorySchemeName = vergi.VergiTuru;
                        //subTevTax.TaxCategorySchemeCode = vergi.VergiKodu;
                        subTevTax.TaxCategorySchemeCode = "650";
                        subTevTax.TaxableAmount = new payFlex.Amount();
                        subTevTax.TaxableAmount.CurrencyCode = Parabirimi;
                        subTevTax.TaxableAmount.Value = vergi.Matrah;
                        subTevTax.Percent = Convert.ToInt32(vergi.VergiOraniYuzde);
                        taxTev.TaxAmount.Value += subTevTax.TaxAmount.Value;
                        AllSubTevTax.Add(subTevTax);
                    }
                    else
                    {
                        payFlex.TaxSubtotal subTax = new payFlex.TaxSubtotal();
                        subTax.TaxAmount = new payFlex.Amount();
                        subTax.TaxAmount.CurrencyCode = Parabirimi;
                        subTax.TaxAmount.Value = vergi.VergiTutari;
                        subTax.TaxCategorySchemeName = vergi.VergiTuru;
                        subTax.TaxCategorySchemeCode = vergi.VergiKodu;
                        subTax.TaxableAmount = new payFlex.Amount();
                        subTax.TaxableAmount.CurrencyCode = Parabirimi;
                        subTax.TaxableAmount.Value = vergi.Matrah;
                        subTax.Percent = vergi.VergiOraniYuzde;
                        AllSubTax.Add(subTax);
                    }
                }

            tax.TaxSubtotal = AllSubTax.ToArray();
            body.TaxTotal = new payFlex.TaxTotal[] { tax };
            #endregion

            if (AllSubTevTax.Count > 0)
            {
                taxTev.TaxSubtotal = AllSubTevTax.ToArray();
                body.WithholdingTaxTotal = new payFlex.TaxTotal[] { taxTev };
            }

            payFlex.MonetaryTotal monTotal = new payFlex.MonetaryTotal();
            monTotal.LineExtensionAmount = new payFlex.Amount();
            monTotal.LineExtensionAmount.CurrencyCode = Parabirimi;
            monTotal.LineExtensionAmount.Value = Matrah;

            monTotal.TaxExclusiveAmount = new payFlex.Amount();
            monTotal.TaxExclusiveAmount.CurrencyCode = Parabirimi;
            monTotal.TaxExclusiveAmount.Value = Matrah;

            monTotal.TaxInclusiveAmount = new payFlex.Amount();
            monTotal.TaxInclusiveAmount.CurrencyCode = Parabirimi;
            monTotal.TaxInclusiveAmount.Value = VergiDahilTutar;

            monTotal.PayableAmount = new payFlex.Amount();
            monTotal.PayableAmount.CurrencyCode = Parabirimi;
            monTotal.PayableAmount.Value = OdenecekTutar;

            body.LegalMonetaryTotal = monTotal;

            List<payFlex.InvoiceLine> AllLine = new List<payFlex.InvoiceLine>();
            #region  Satirlar
            bool muafiyetEklendi = false;
            foreach (Satir satir in Satirlar)
            {
                payFlex.InvoiceLine line = new payFlex.InvoiceLine();
                line.InvoicedQuantityUnitCode = satir.Birim;
                line.InvoicedQuantityValue = satir.Miktar;
                line.LineExtensionAmount = new payFlex.Amount();
                line.LineExtensionAmount.CurrencyCode = Parabirimi;
                line.LineExtensionAmount.Value = satir.Matrah;


                payFlex.TaxTotal lineTax = new payFlex.TaxTotal();
                lineTax.TaxAmount = new payFlex.Amount();
                lineTax.TaxAmount.CurrencyCode = Parabirimi;
                lineTax.TaxAmount.Value = satir.VergiTutari;

                //KG: Ben ekledim. Tuba Hanım'la konuşmamıza istinaden;
                //Bizim faturalarda tevkifat sadece fatura sonunda tek bir oran olarak giriliyor.
                //innova ise satır bazında bu oranların girilmesini, matrahın da ona göre hesaplanmasını istiyor.
                //o yüzden aşağıdaki güncelleme yapıldı.


                if (AllSubTevTax.Count == 1)
                {
                    payFlex.TaxSubtotal tev = AllSubTevTax[0];

                    payFlex.TaxTotal linetaxTev = new payFlex.TaxTotal();
                    linetaxTev.TaxAmount = new payFlex.Amount();
                    linetaxTev.TaxAmount.CurrencyCode = Parabirimi;


                    payFlex.TaxSubtotal lineTevTax = new payFlex.TaxSubtotal();
                    lineTevTax.TaxAmount = new payFlex.Amount();
                    lineTevTax.TaxAmount.CurrencyCode = Parabirimi;

                    lineTevTax.TaxableAmount = new payFlex.Amount();
                    lineTevTax.TaxableAmount.CurrencyCode = Parabirimi;

                    lineTevTax.TaxableAmount.Value = satir.VergiTutari;
                    lineTevTax.Percent = Convert.ToInt32(tev.Percent);
                    lineTevTax.TaxAmount.Value = lineTevTax.TaxableAmount.Value * (tev.Percent / 100);

                    linetaxTev.TaxAmount.Value = lineTevTax.TaxAmount.Value;

                    //if (tev.Percent != 50)
                    //    throw new ApplicationException("Tevkifat kodu gerekli! Yazılım ekibiyle iletişime geçin.");

                    lineTevTax.TaxCategorySchemeName = "KDV TEVKIFAT";
                    //lineTevTax.TaxCategorySchemeCode = vergi.VergiKodu;
                    lineTevTax.TaxCategorySchemeCode = "650";


                    //taxTev.TaxSubtotal = new payFlex.TaxSubtotal[] { lineTevTax };
                    linetaxTev.TaxSubtotal = new payFlex.TaxSubtotal[] { lineTevTax };
                    line.WithholdingTaxTotal = new payFlex.TaxTotal[] { linetaxTev };


                    //lineTaxTev.TaxSubtotal = ??
                }
                else if (AllSubTevTax.Count > 1)
                    throw new ApplicationException("Birden fazla tevkifat bilgisi var! Yazılım ekibiyle iletişime geçin.");

                payFlex.TaxSubtotal lineSubTax = new payFlex.TaxSubtotal();
                lineSubTax.TaxAmount = new payFlex.Amount();
                lineSubTax.TaxAmount.CurrencyCode = Parabirimi;
                lineSubTax.TaxAmount.Value = satir.VergiTutari;

                if (satir.VergiTutari == 0)
                {
                    if (Vergiler.Count > 0 && !muafiyetEklendi)
                    {
                        payFlex.TaxSubtotal subTax = new payFlex.TaxSubtotal();

                        subTax.TaxAmount = new payFlex.Amount();
                        subTax.TaxAmount.CurrencyCode = Parabirimi;
                        subTax.TaxAmount.Value = 0;
                        subTax.TaxCategorySchemeName = "KDV";
                        subTax.TaxCategorySchemeCode = "0015";
                        subTax.TaxableAmount = new payFlex.Amount();
                        subTax.TaxableAmount.CurrencyCode = Parabirimi;
                        subTax.TaxableAmount.Value = 0;
                        subTax.Percent = 0;

                        subTax.TaxCategoryExemptionReason = "KDV siz";
                        subTax.TaxCategoryExemptionReasonCode = "351";

                        //body.InvoiceTypeCode = (int)Temel.FaturaTipi.Istisna;

                        AllSubTax.Add(subTax);

                        tax.TaxSubtotal = AllSubTax.ToArray();
                        body.TaxTotal = new payFlex.TaxTotal[] { tax };

                        muafiyetEklendi = true;
                    }

                    lineSubTax.TaxCategoryExemptionReason = "KDV siz";
                    lineSubTax.TaxCategoryExemptionReasonCode = "350";

                    //body.InvoiceTypeCode = (int)Temel.FaturaTipi.Istisna;
                }


                lineSubTax.TaxCategorySchemeName = "KDV GERCEK";
                lineSubTax.TaxCategorySchemeCode = "0015";
                lineSubTax.Percent = satir.VergiOraniYuzde;

                lineSubTax.TaxableAmount = new payFlex.Amount();
                lineSubTax.TaxableAmount.CurrencyCode = Parabirimi;
                lineSubTax.TaxableAmount.Value = satir.Matrah;

                lineTax.TaxSubtotal = new payFlex.TaxSubtotal[] { lineSubTax };
                line.TaxTotal = lineTax;

                line.Item = new payFlex.Item();
                line.Item.Name = satir.Urun;
                line.Item.Description = satir.UrunDetay;

                line.Price = new payFlex.Amount();
                line.Price.CurrencyCode = Parabirimi;
                line.Price.Value = satir.BirimFiyat;

                AllLine.Add(line);
            }

            #endregion
            body.InvoiceLine = AllLine.ToArray();

            if (SirketId != 4)//Aker sipariş nonun efaturada gözükmesini istemiyor
            {
                body.OrderReference = new payFlex.OrderReference();
                body.OrderReference.ID = TakipNo.ToStringNN();
                body.OrderReference.IssueDate = Tarih;
            }

            gidenFatura.Body = body;

            sendReq.Invoices = new payFlex.OutgoingInvoice[] { gidenFatura };

            payFlex.SendInvoicesResponse response = payer.SendInvoices(sendReq);

            payFlex.InvoiceResultItem ri = response.Items[0];

            eFaturaNo = ri.InvoiceNumber.ToStringNN();

            PayFlexDurum = ri.ResponseDescription.Trim();
            URL = ri.ViewUrl;
            PayFlexId = ri.ReferenceNumber;

            if (PayFlexDurum != "")
                throw new ApplicationException(PayFlexDurum);

            AppSession.DataManager.ExecuteNonQuery(Schema + "InsGidenEFatura", TakipNo, eFaturaNo, PayFlexId, URL, PayFlexDurum, ZarfDurum, FaturaDurum, Tamamlandi, sendReq.AcceptanceDateTime, SirketId);

            DurumGuncelle(PayFlexId);
        }

        public void DurumGuncelle(long payFlexId)
        {
            if (payFlexId > 0)
            {
                eFatura.payFlex.InvoiceInquiryRequest invoiceReq = new payFlex.InvoiceInquiryRequest();
                invoiceReq.Header = Anahtar;
                invoiceReq.ReferenceNumber = payFlexId;

                payFlex.InvoiceInquiryResponse resp = payer.InvoiceInquiry(invoiceReq);

                ZarfDurum = resp.EnvelopeStatusDescription.Trim();
                FaturaDurum = resp.InvoiceStatusDescription.Trim();
                Tamamlandi = resp.IsCompleted;

                AppSession.DataManager.ExecuteNonQuery("UpdDurum", payFlexId, ZarfDurum, FaturaDurum, Tamamlandi);
            }
            else
                throw new ApplicationException("PayFlexId Boş !");
        }

        public void GonderilmeyenFaturalariGuncelle()
        {
            //payReport.GetSummaryDailyRequest reqHeader = new payReport.GetSummaryDailyRequest();
            //reqHeader.Header = RaporAnahtar;
            //reqHeader.StartDate = new DateTime(2014, 3, 9);
            //reqHeader.EndDate = new DateTime(2015, 1, 15);
            //payReport.GetSummaryDailyResponse resHeader = reportService.GetSummaryDaily(reqHeader);

            payReport.GetDetailRequest reqDetail = new payReport.GetDetailRequest();
            reqDetail.Header = RaporAnahtar;
            reqDetail.StartDate = new DateTime(2014, 3, 31);
            reqDetail.EndDate = new DateTime(2014, 4, 1);


            payReport.GetDetailResponse resDetail = reportService.GetDetail(reqDetail);

            DataTable dtNotSent = AppSession.DataManager.ExecuteDataTable("GetGonderilmeyenEfatura");

            foreach (payReport.ReconcilationDetail detail in resDetail.ReconcilationDetails)
            {
                int trackNo = 0;
                if (int.TryParse(detail.TrackNumber, out trackNo))
                {
                    DataRow[] drs = dtNotSent.Select(string.Format("nStokFisiId = {0}", trackNo));
                    if (drs.Length > 0)
                        if ((decimal)drs[0]["Tutar"] == detail.InvoiceAmount)
                            drs[0]["PayFlexId"] = detail.ReferenceNumber;
                }
            }

            if (dtNotSent.Select("PayFlexId is not null").Length > 0)
            {
                string xml = dtNotSent.Select("PayFlexId is not null").CopyToDataTable().Serialize();
                AppSession.DataManager.ExecuteNonQuery("InsPayFlexId", xml);
            }
        }

        public void TumEFaturaMukellefGuncelle()
        {

            eFaturaMukellefGuncelle(true, 1);
            eFaturaMukellefGuncelle(true, 2);
            eFaturaMukellefGuncelle(true, 3);
            eFaturaMukellefGuncelle(true, 4);
            eFaturaMukellefGuncelle(true, 5);

            XtraMessageBox.Show("e-Fatura mükelleflerinin güncellenmesi tamamlandı. Çalışmanıza devam edebilirsiniz.", "Uyarı", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        public void eFaturaMukellefGuncelle(bool Tumu, int sirketId)
        {
            payFlex.CustomerInquiryRequest req = new payFlex.CustomerInquiryRequest();
            req.Header = Anahtar;

            DataTable dt = AppSession.DataManager.ExecuteDataTable("[S" + sirketId + "]." + "GetTanimsizCari", Tumu, sirketId);
            dt.Columns.Add("eFatura", typeof(Int16));
            dt.Columns.Add("PostaKutusu", typeof(string));
            dt.Columns.Add("MukellefBaslangic", typeof(DateTime));

            List<string> VKNs = new List<string>();

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                VKNs.Add(dt.Rows[i]["VKN"].ToString());

                if (VKNs.Count == 100 || i == dt.Rows.Count - 1)
                {
                    req.IdentityNumbers = VKNs.ToArray();
                    payFlex.CustomerInquiryResponse resp = payer.CustomerInquiry(req);

                    foreach (payFlex.Customer customer in resp.Customers)
                    {
                        DataRow[] founds = dt.Select("VKN='" + customer.IdentityNumber + "'");
                        foreach (DataRow found in founds)
                        {
                            if (customer.IsExists)
                            {
                                found["eFatura"] = true;
                                if (customer.ReceiverAliasses.Length > 0)
                                {
                                    found["PostaKutusu"] = customer.ReceiverAliasses[0].Alias;
                                    found["MukellefBaslangic"] = customer.CustomerCreatedOn;
                                }
                                else
                                {
                                    found["eFatura"] = false;
                                    found["PostaKutusu"] = "HATALI";
                                }

                            }
                            else
                                found["eFatura"] = false;
                        }
                    }

                    VKNs = new List<string>(); //sıfırla
                }
            }


            string xml = dt.DefaultView.ToTable(false, "CariId", "efatura", "PostaKutusu", "MukellefBaslangic").Serialize();
            AppSession.DataManager.ExecuteNonQuery("UpdCariEFatura", xml, sirketId);
        }

        public DataSet GelenFaturaSorgula(long PayFlexId = 0)
        {

            DataSet ds = new DataSet();

            //return null;
            int RequestNumber = 0;

            if (PayFlexId > 0)
                RequestNumber = (int)AppSession.DataManager.ExecuteScalar("GetRequestNumberByPayFlexId", PayFlexId);
            else
                RequestNumber = AppSession.DataManager.ExecuteScalar("GetRequestNumber", SirketId).ToIntZero();

            //RequestNumber = 24578;

            payFlex.GetInvoicesRequest reqInc = new payFlex.GetInvoicesRequest();
            reqInc.Header = Anahtar;

            reqInc.MaxItemsToReturn = 10; //İstenilen fatura adedi
            reqInc.AcceptanceDateTime = DateTime.Now; //Yeni bir istek gönderirken dolu olması gereken bir kere mark olduktan sonra anlamı kalmayan tarih

            reqInc.RequestNumber = RequestNumber;

            //reqInc.ViewContentType = 2;


            payFlex.GetInvoicesResponse res = payer.GetInvoices(reqInc);

            if (res.Header.Status != 0)
                throw new ApplicationException("HATA:" + res.Header.Message);



            DataTable dtMaster = new DataTable();

            dtMaster.Columns.Add("PayFlexId", typeof(int));
            dtMaster.Columns.Add("PayFlexAlinanTarih", typeof(DateTime));
            dtMaster.Columns.Add("RequestNumber", typeof(int));
            dtMaster.Columns.Add("URL", typeof(string));

            dtMaster.Columns.Add("ProfileId", typeof(int));
            dtMaster.Columns.Add("Gonderen", typeof(string));
            dtMaster.Columns.Add("nFirmaId", typeof(int));
            dtMaster.Columns.Add("GonderenVKNTipi", typeof(string));
            dtMaster.Columns.Add("GonderenVKN", typeof(string));
            dtMaster.Columns.Add("GonderenAdres", typeof(string));
            dtMaster.Columns.Add("SenderIdentityNumber", typeof(string));

            dtMaster.Columns.Add("eFaturaNo", typeof(string));
            dtMaster.Columns.Add("FaturaTarihi", typeof(DateTime));
            dtMaster.Columns.Add("AsilMi", typeof(bool));
            dtMaster.Columns.Add("FaturaTipi", typeof(int));

            dtMaster.Columns.Add("Matrah", typeof(decimal));
            dtMaster.Columns.Add("KDVTutari", typeof(decimal));
            dtMaster.Columns.Add("Iskonto", typeof(decimal));
            dtMaster.Columns.Add("Arttirim", typeof(decimal));
            dtMaster.Columns.Add("Yuvarlama", typeof(decimal));
            dtMaster.Columns.Add("Tutar", typeof(decimal));
            dtMaster.Columns.Add("OdenecekTutar", typeof(decimal));

            dtMaster.Columns.Add("DovizCinsi", typeof(string));
            dtMaster.Columns.Add("DovizKuru", typeof(decimal));
            dtMaster.Columns.Add("ParaBirimi", typeof(string));
            dtMaster.Columns.Add("Notlar", typeof(string));

            DataTable dtDetail = new DataTable();
            dtDetail.Columns.Add("PayFlexId", typeof(int));
            dtDetail.Columns.Add("MalHizmet", typeof(string));
            dtDetail.Columns.Add("nStokId", typeof(int));
            dtDetail.Columns.Add("Miktar", typeof(decimal));
            dtDetail.Columns.Add("MiktarBirimi", typeof(string));
            dtDetail.Columns.Add("BirimFiyat", typeof(decimal));
            dtDetail.Columns.Add("Iskonto", typeof(decimal));
            dtDetail.Columns.Add("Arttirim", typeof(decimal));
            dtDetail.Columns.Add("KDVOrani", typeof(decimal));
            dtDetail.Columns.Add("KDVTutari", typeof(decimal));
            dtDetail.Columns.Add("MalHizmetTutari", typeof(decimal));
            dtDetail.Columns.Add("Aciklama", typeof(string));

            DataTable dtVergi = new DataTable();
            dtVergi.Columns.Add("PayFlexId", typeof(int));
            dtVergi.Columns.Add("VergiMatrahi", typeof(decimal));
            dtVergi.Columns.Add("VergiTutari", typeof(decimal));
            dtVergi.Columns.Add("VergiOrani", typeof(decimal));
            dtVergi.Columns.Add("VergiTuru", typeof(string));
            dtVergi.Columns.Add("VergiKodu", typeof(string));

            ds.Tables.Add(dtMaster);
            ds.Tables.Add(dtDetail);
            ds.Tables.Add(dtVergi);

            if (res.Invoices.Length == 0)
            {
                AppSession.DataManager.ExecuteNonQuery("UpdReq", RequestNumber);
                return ds;
            }


            foreach (payFlex.IncomingInvoice invoice in res.Invoices)
            {
                if (PayFlexId > 0 && invoice.Header.ReferenceNumber != PayFlexId)
                    continue;

                payFlex.IncomingInvoiceHeader header = invoice.Header;
                payFlex.InvoiceBody body = invoice.Body;

                DataRow drMaster = dtMaster.NewRow();
                drMaster["PayFlexId"] = header.ReferenceNumber;
                drMaster["PayFlexAlinanTarih"] = header.ReceiveDateTime;
                drMaster["RequestNumber"] = RequestNumber;
                drMaster["URL"] = header.ViewUrl;

                drMaster["ProfileID"] = body.ProfileID;

                payFlex.Party gonderen = body.AccountingSupplierParty.Party;

                drMaster["Gonderen"] = gonderen.PartyName;
                drMaster["GonderenVKNTipi"] = gonderen.PartyIdentifications[0].SchemeID;
                drMaster["GonderenVKN"] = gonderen.PartyIdentifications[0].Value;

                drMaster["SenderIdentityNumber"] = header.SenderIdentityNumber;


                List<string> adres = new List<string>();


                if (gonderen.PostalAddress.CitySubdivisionName.ToStringNN() != "")
                    adres.Add(gonderen.PostalAddress.CitySubdivisionName.Trim());

                if (gonderen.PostalAddress.CityName.ToStringNN() != "")
                    adres.Add(gonderen.PostalAddress.CityName.Trim());

                if (gonderen.PostalAddress.Country.Name.ToStringNN() != "")
                    adres.Add(gonderen.PostalAddress.Country.Name.Trim());

                drMaster["GonderenAdres"] = string.Join(" / ", adres.ToList());
                drMaster["eFaturaNo"] = body.ID;

                drMaster["AsilMi"] = !body.CopyIndicator;


                drMaster["FaturaTipi"] = body.InvoiceTypeCode;

                if (body.InvoiceTypeCode == 3)
                {
                    if (body.WithholdingTaxTotal.Count() > 1)
                        throw new ApplicationException("Birden fazla tevkifat bilgisi var! Yazılım ekibiyle iletişime geçin.");

                    payFlex.TaxTotal tev = body.WithholdingTaxTotal[0];
                    foreach (payFlex.TaxSubtotal tevTax in tev.TaxSubtotal)
                    {
                        decimal vergiMatrahi = 0;
                        if (tevTax.TaxableAmount != null)
                            vergiMatrahi = tevTax.TaxableAmount.Value;
                        else if (tev.TaxSubtotal.Count() == 1)
                            vergiMatrahi = body.LegalMonetaryTotal.TaxExclusiveAmount.Value;

                        var VergiTutari = tevTax.TaxAmount.Value;
                        var VergiOrani = tevTax.Percent;
                        var VergiTuru = tevTax.TaxCategorySchemeName;
                        var VergiKodu = tevTax.TaxCategorySchemeCode;

                        DataRow drVergi = dtVergi.NewRow();

                        drVergi["PayFlexId"] = header.ReferenceNumber;
                        drVergi["VergiMatrahi"] = vergiMatrahi;
                        drVergi["VergiTutari"] = VergiTutari;
                        drVergi["VergiOrani"] = VergiOrani;
                        drVergi["VergiTuru"] = VergiTuru;
                        drVergi["VergiKodu"] = VergiKodu;

                        dtVergi.Rows.Add(drVergi);
                    }
                }


                drMaster["FaturaTarihi"] = body.IssueDateTime;

                drMaster["Matrah"] = body.LegalMonetaryTotal.TaxExclusiveAmount.Value;
                drMaster["KDVTutari"] = body.TaxTotal[0].TaxAmount.Value;

                if (body.TaxTotal.Count() > 1)
                    XtraMessageBox.Show(body.ID + " no'lu faturada birden fazla vergi bilgisi var! Bu faturanın manual düzenlenmesi gerekiyor !!!", "Uyarı", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                //   throw new ApplicationException("Birden fazla vergi bilgisi var! Yazılım ekibiyle iletişime geçin.");

                #region GelenEFaturaVergi
                foreach (payFlex.TaxSubtotal tax in body.TaxTotal[0].TaxSubtotal)
                {
                    decimal vergiMatrahi = 0;
                    if (tax.TaxableAmount != null)
                        vergiMatrahi = tax.TaxableAmount.Value;
                    else if (body.TaxTotal[0].TaxSubtotal.Count() == 1)
                        vergiMatrahi = body.LegalMonetaryTotal.TaxExclusiveAmount.Value;
                    var VergiTutari = tax.TaxAmount.Value;
                    var VergiOrani = tax.Percent;
                    var VergiTuru = tax.TaxCategorySchemeName;
                    var VergiKodu = tax.TaxCategorySchemeCode;

                    if (VergiOrani == 0 && VergiTutari > 0 && vergiMatrahi > 0)
                        VergiOrani = decimal.Round(VergiTutari / vergiMatrahi * 100, 4);

                    DataRow drVergi = dtVergi.NewRow();

                    drVergi["PayFlexId"] = header.ReferenceNumber;
                    drVergi["VergiMatrahi"] = vergiMatrahi;
                    drVergi["VergiTutari"] = VergiTutari;
                    drVergi["VergiOrani"] = VergiOrani;
                    drVergi["VergiTuru"] = VergiTuru;
                    drVergi["VergiKodu"] = VergiKodu;

                    dtVergi.Rows.Add(drVergi);
                }
                #endregion

                if (body.LegalMonetaryTotal.AllowanceTotalAmount != null)
                    drMaster["Iskonto"] = body.LegalMonetaryTotal.AllowanceTotalAmount.Value;
                if (body.LegalMonetaryTotal.ChargeTotalAmount != null)
                    drMaster["Arttirim"] = body.LegalMonetaryTotal.ChargeTotalAmount.Value;
                if (body.LegalMonetaryTotal.PayableRoundingAmount != null)
                    drMaster["Yuvarlama"] = body.LegalMonetaryTotal.PayableRoundingAmount.Value;

                drMaster["Tutar"] = body.LegalMonetaryTotal.TaxInclusiveAmount.Value;
                drMaster["OdenecekTutar"] = body.LegalMonetaryTotal.PayableAmount.Value;
                drMaster["ParaBirimi"] = body.LegalMonetaryTotal.TaxInclusiveAmount.CurrencyCode;

                if (body.PricingExchangeRate != null)
                {
                    //drMaster["ParaBirimi"] = body.PricingExchangeRate.SourceCurrencyCode;
                    drMaster["DovizKuru"] = body.PricingExchangeRate.CalculationRate;
                    drMaster["DovizCinsi"] = body.PricingExchangeRate.TargetCurrencyCode;
                }
                if (drMaster["ParaBirimi"].ToStringNN() == "")
                    drMaster["ParaBirimi"] = body.DocumentCurrencyCode;
                drMaster["Notlar"] = "";

                foreach (string note in body.Notes)
                {
                    drMaster["Notlar"] += note + "\n";
                }

                dtMaster.Rows.Add(drMaster);

                #region GelenEFaturaLines

                bool autoFix = true;

                DataRow[] dtVergiCurrent = dtVergi.Select("PayFlexId = " + header.ReferenceNumber);

                if (dtVergiCurrent.Length == 1)
                {
                    decimal satirTutarlari = 0;
                    foreach (payFlex.InvoiceLine line in body.InvoiceLine)
                    {
                        satirTutarlari += line.LineExtensionAmount.Value;

                        if (line.TaxTotal != null)
                        {
                            if (line.TaxTotal.TaxSubtotal[0].Percent > 0 && line.TaxTotal.TaxAmount.Value > 0)
                            {
                                autoFix = false;
                                break;
                            }
                        }
                    }
                    decimal hesaplananKDV = (satirTutarlari * ((decimal)dtVergiCurrent[0]["VergiOrani"])).ToIntNN();
                    decimal headerKDV = (dtVergiCurrent[0]["VergiTutari"].ToDecimalNN() * 100).ToIntNN();
                    if (hesaplananKDV != headerKDV)
                        autoFix = false;
                }
                else
                    autoFix = false;


                foreach (payFlex.InvoiceLine line in body.InvoiceLine)
                {
                    var QtyCode = line.InvoicedQuantityUnitCode;
                    var Qty = line.InvoicedQuantityValue;
                    var Tutar = line.LineExtensionAmount.Value;
                    var Price = line.Price.Value;
                    VergiToplami = 0;
                    decimal kDVOrani = 0;

                    if (autoFix)
                    {
                        kDVOrani = (decimal)dtVergiCurrent[0]["VergiOrani"];
                        VergiToplami = Tutar * kDVOrani / 100;

                    }
                    else
                    {
                        if (line.TaxTotal != null)
                        {
                            VergiToplami = line.TaxTotal.TaxAmount.Value;
                            foreach (payFlex.TaxSubtotal lineTax in line.TaxTotal.TaxSubtotal)
                            {
                                if (lineTax.TaxCategorySchemeCode == "0015")
                                    kDVOrani = lineTax.Percent;
                            }

                        }
                    }



                    DataRow drDetail = dtDetail.NewRow();
                    drDetail["PayFlexId"] = header.ReferenceNumber;
                    drDetail["MalHizmet"] = line.Item.Name;
                    drDetail["Miktar"] = Qty;
                    drDetail["MiktarBirimi"] = Temel.ConvertToBirim(QtyCode);
                    drDetail["BirimFiyat"] = Price;

                    //ia: iskonto , artırım
                    if (line.AllowanceCharge != null)
                    {
                        var iaVarmi = line.AllowanceCharge.ChargeIndicator;
                        var iaNeden = line.AllowanceCharge.AllowanceChargeReason;
                        var iaOran = line.AllowanceCharge.MultiplierFactorNumeric;
                        var iaTutar = line.AllowanceCharge.Amount.Value;
                        decimal iaMatrah;
                        if (line.AllowanceCharge.BaseAmount != null)
                            iaMatrah = line.AllowanceCharge.BaseAmount.Value;

                        if (iaVarmi)
                            drDetail["Arttirim"] = iaTutar;
                        else
                            drDetail["Iskonto"] = iaTutar;
                    }

                    drDetail["KDVOrani"] = kDVOrani;
                    drDetail["KDVTutari"] = VergiToplami;
                    drDetail["MalHizmetTutari"] = Tutar;

                    if (line.Item.Description != null || line.Item.ManufacturersItemIdentification != null)
                    {
                        string note = line.Item.Description.ToStringNN().Replace('\n', ' ');

                        string urun = line.Item.ManufacturersItemIdentification.ToStringNN();

                        if (urun != "")
                        {
                            if (note == "")
                                note = urun;
                            else
                                note = note + " * " + urun;
                        }

                        drDetail["Aciklama"] = note;

                    }

                    dtDetail.Rows.Add(drDetail);
                }
            }
                #endregion

            if (dtMaster.Rows.Count > 0)
            {
                string FaturaXML = dtMaster.Serialize();
                string FaturaSatirXML = dtDetail.Serialize();
                string FaturaVergiXML = dtVergi.Serialize();

                if (PayFlexId == 0)
                    AppSession.DataManager.ExecuteNonQuery("InsGelenEFatura", FaturaXML, FaturaSatirXML, FaturaVergiXML, SirketId);

                return ds;
            }
            return ds;
        }

        public void TicariFaturaYanitla(long PayFlexId, int Reply)
        {
            payFlex.ReplylInvoicesRequest req = new payFlex.ReplylInvoicesRequest();
            req.Header = Anahtar;

            req.AcceptanceDateTime = DateTime.Now;

            eFatura.payFlex.ReplyInvoiceItem replyItem = new payFlex.ReplyInvoiceItem();
            replyItem.ReferenceNumber = PayFlexId;
            replyItem.ReplyState = Reply;
            replyItem.ReplyDescription = "Ticari Yanıt";

            req.Items = new payFlex.ReplyInvoiceItem[] { replyItem };

            payFlex.ReplylInvoicesResponse resp = payer.ReplyInvoices(req);

            int ResponseStatus = resp.Items[0].ResponseStatus;
            string ResponseDescription = resp.Items[0].ResponseDescription;
            string ResponseCode = resp.Items[0].ResponseCode;
            if (ResponseStatus != 0)
                DevExpress.XtraEditors.XtraMessageBox.Show(ResponseDescription, "Hata", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);

            AppSession.DataManager.ExecuteNonQuery("UpdTicariStatu", PayFlexId, Reply, ResponseStatus, ResponseDescription);
        }

    }
}
